package servlet.goods;


import util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/addgoods.do")
@MultipartConfig
public class GoodsAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String goodsName = req.getParameter("goods_name");
        int type = Integer.parseInt(req.getParameter("type"));
        String goodsprice = req.getParameter("goods_price");
        String goodsdesc = req.getParameter("goods_desc");
        String supplier = req.getParameter("supplier");
        int qty = Integer.parseInt(req.getParameter("num"));
        Part part = req.getPart("goods_img");
        String fileName = part.getSubmittedFileName();
        String path = "D:\\ideaproject\\shopping\\src\\main\\webapp\\images\\";
        path += fileName;
        part.write(path);
        DbUtil dbu = new DbUtil();
        String sql = "insert into goods(goods_name,type_id,goods_price,goods_desc,supplier,qty,goods_pic) values('"+goodsName+"',"+type+",'"+goodsprice+"','"+goodsdesc+"','"+supplier+"',"+qty+",'"+fileName+"')";
        System.out.println(sql);
        if (dbu.executeUpdate(sql)<=0){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>alert('添加成功');</script>");
            resp.sendRedirect("first_admin.jsp");
        }else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>alert('添加失败');</script>");
            resp.sendRedirect("first_admin.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
